import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import router from 'umi/router';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import SelectDeptTree from '@/components/SelectDeptTree';
import styles from './StaffInfoList.less';
import '@/assets/iconfont/iconfont';
import {
    Row,
    Col,
    Form, 
    Input,
    Select, 
    Button,
    message,
    Upload,
    Icon,
    Card,
    DatePicker,
    InputNumber,
    Cascader,
    Modal
} from 'antd';
const FormItem = Form.Item;
const { Option } = Select;
/* eslint react/no-multi-comp:0 */
@connect(({ prostaff, loading }) => ({
    prostaff,
    loading: loading.models.prostaff,
}))

@Form.create()
class StaffCreateForm extends PureComponent {

	
	state = {
	   file: null,
	   imageUrl: null,
	   flag: "1",
	   visible: false,
	   visiblePhoto: false,
	   photoNum: 0,
	   requestModelName:"prostaff",
	   getDeptTreeBySelectTree: "",
	   staffName: "",
	   staffId: ""
	};

	
	componentDidMount () {
  		const { dispatch } = this.props;
  		dispatch({
	    	type: 'prostaff/get_all_city',
	    	payload: {
	    		dictid:"AB"
	    	}
	    });
		dispatch({
			type: 'prostaff/get_all_post_for_user',
		});
	}
	
	selectedDeptTreeValue = (deptRecord) => {
		this.setState({
			getDeptTreeBySelectTree: deptRecord
		})
	}			
				
	beforeUpload = file => {
		
		this.setState({
        	file:file,
	  	});

		if(window.FileReader) {
	      	const reader = new FileReader();
	      
	      	reader.readAsDataURL(file);
	      
			reader.addEventListener('load', () => {
			  	
			  	this.setState({
		          imageUrl:reader.result,
		          loading: false,
		          photoNum: 1
		      	})

		  	});
		}

		const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.tyle === 'image/jpg';
	  	if (!isJpgOrPng) {
	    	message.error('You can only upload JPG/PNG file!');
	  	}
	 	const isLt2M = file.size / 1024 / 1024 < 2;
	  	if (!isLt2M) {
	    	message.error('Image must smaller than 2MB!');
	  	}
	  	return isJpgOrPng && isLt2M;
	}
  	
 	onChange = (value) => {

	};
	
	handleChange = (value,e) => {
		const { dispatch } = this.props;
		this.setState({
			flag: value
		})
	};
	
	handleUpdate = e => {
	    this.setState({
	      visible: false,
	    });
	    router.push({
		  pathname: '/staff/updatestaff',
		  query: {
		    id: this.state.staffId,
		  },
		});
	};
	
	handleAdd = e => {
	    this.setState({
	      visible: false,
	    });
	};
	
  handleSubmit = (event) => {
	    event.preventDefault();
	
	    const {  dispatch,form } = this.props;
	    const {  getDeptTreeBySelectTree } = this.state;
		
	    form.validateFields(async(error, values) => {
	      	if (!error) {
	      		form.resetFields();
	      		values.entry_time = moment(values.entry_time._d).format("YYYY-MM-DD");
	      		if(values.date_of_birth) {
	      			values.date_of_birth = moment(values.date_of_birth._d).format("YYYY-MM-DD");
	      		}
					if(values.become_worker_time) {
						values.become_worker_time = moment(values.become_worker_time._d).format("YYYY-MM-DD");
					}
					if(getDeptTreeBySelectTree) {
						values.dept_id = getDeptTreeBySelectTree.triggerNode.props.dataRef.dept_id;
						values.dept = getDeptTreeBySelectTree.triggerNode.props.dataRef.title;
					}
					if(values.post) {
						values.post_name = values.post.label;
						values.post_id = values.post.key;
					}
					const bodymap = {
		              pname: values.pname,
		              phone: values.phone,
		              gender:values.gender,
		              idcard:values.idcard,
		              date_of_birth: values.date_of_birth,
		              place_of_origin: values.place_of_origin,
		              place_of_domicile: values.place_of_domicile,
		              email: values.email,
		              emergency_contact_name: values.emergency_contact_name,
		              emergency_contact_phone: values.emergency_contact_phone,
		              bank_card_number: values.bank_card_number,
		              open_bank: values.open_bank,
		              entry_time: values.entry_time,
		              dept: values.dept,
		              dept_id: values.dept_id,
		              post_name: values.post_name,
		              post_id: values.post_id,
		              from_of_employment: values.from_of_employment,
		              become_worker_time: values.become_worker_time,
		              become_worker_type: values.become_worker_type,
		              management_form: values.management_form,
		              job_number: values.job_number,
		              working_city: values.working_city
		           	};
		           	const formData = new FormData();
		            formData.append('uploadfile', this.state.file);
				    formData.append('bodymap', JSON.stringify(bodymap));
				        await dispatch({
			              	type: 'prostaff/insert_for_staff',
			              	payload: {
								formdata: formData
			              	},
			              	callback:(res) => {
					        	if(res.success) {
											message.success('添加成功');
											this.setState({
									      visible: true,
									      staffName: res.datarecord.pname,
									      staffId: res.datarecord.id
									    });
					        	}else {
				        			message.success('添加失败');
					        	}
		  					}
			          });
		    }else{
		        return false;
		    }
	
	    })
	
	}
  	
  //关闭继续添加弹窗
  handleStaffCancel = () => {
  		this.setState({
	      visible: false,
	    });
  }
	
	handleCancel = () => {
			this.setState({
	      visiblePhoto: false,
	    });
	}
	
	handleOk = () => {
		this.setState({
	      visiblePhoto: false,
	    });
	}
	
	staffPhotoShow = () => {
		this.setState({
	      visiblePhoto: true,
	    });
	}
  render () {
  	
	const formItemLayout = {
     	labelCol: { span: 8 },
       	wrapperCol: { span: 14 },
	};

  	const { getFieldDecorator } = this.props.form
    
	const uploadButton = (
      <div style={{marginTop: '30px'}}>
      	<svg className={`${styles.icon} ${styles.staffPhoto}` } aria-hidden="true">
          <use xlinkHref="#icon-shangchuanzhaopian"></use>
        </svg>
        <div className="ant-upload-text">上传照片</div>
      </div>
    );
  const { imageUrl,flag,photoNum,staffName } = this.state;
	
	const {
		prostaff: {
			selectDeptTree,
			cascaderList,
			postForUser
		},
		dispatch
	} = this.props;
	
	const parentDeptTreeMethod = {
		dispatch: dispatch,
		selectDeptTree: selectDeptTree,
		selectedDeptTreeValue: this.selectedDeptTreeValue,
		requestModelName: this.state.requestModelName
	}
    return (
    	<PageHeaderWrapper title="添加员工">
    		<Modal
    	  centered
    	  width={400}
		  	bodyStyle={{textAlign: 'center',padding: '40px 30px 10px 30px'}}
        visible={this.state.visible}
        onCancel={this.handleStaffCancel}
        footer={false}
        >
          <p style={{fontSize: '16px'}}>添加成功</p>
          <p>{staffName}</p>
          <Button  style={{fontSize: '12px',marginRight: '8px',marginBottom: '20px'}} onClick = {this.handleAdd}>继续添加</Button>
          <Button  type="primary" style={{fontSize: '12px'}} onClick = {this.handleUpdate}>完善员工信息</Button>
        </Modal>
        <Modal
    	  	centered
    	  	title="员工照片"
    	  	width={800}
		  		bodyStyle={{textAlign: 'center'}}
          visible={this.state.visiblePhoto}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
        >
					<Upload 
			      	accept=".jpeg,.png,.jpg"
			        listType="picture-card"
			        className="avatar-uploader"
			        showUploadList={false}
			        beforeUpload={this.beforeUpload}
			        style={{display: 'table',width:'120px',height: '120px',margin: '0 auto',verticalAlign:'top'}}
			      >
		        	{imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
		      </Upload>
	      	<div>图片格式为JPG/JPEG/PNG,大小在2MB内</div>
    		</Modal>
    <Card bordered={false}>
    <div className="demo-container">

  	<Form  {...formItemLayout} onSubmit={this.handleSubmit}>

    <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
    
        <Col md={12} sm={24}>
          <FormItem  label="姓名">
              {getFieldDecorator('pname', {
              rules: [{ required: true, message: '请输入1-10个字符的姓名',max: 10}],
              })(<Input placeholder="1-10个字符"/>)}
          </FormItem>
        </Col>

        <Col md={12} sm={24}>
          <FormItem  label="手机">
              {getFieldDecorator('phone', {
              rules: [{ required: true, message: '手机号码格式不符！',  pattern:/^1(3|4|5|6|7|8|9)\d{9}$/ }],
              })(<Input placeholder="正规手机号格式" />)}
          </FormItem>
        </Col>

    </Row>
    
    <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
    
        <Col md={12} sm={24}>
          <FormItem  label="性别">
              {getFieldDecorator('gender')(
              	<Select placeholder="请选择" style={{ width: '100%' }}>
                    <Select.Option key="01">男</Select.Option>
                    <Select.Option key="02">女</Select.Option>
                </Select>
              )}
          </FormItem>
        </Col>

        <Col md={12} sm={24}>
          <FormItem  label="身份证号">
              {getFieldDecorator('idcard', {
              rules: [{ required: false, message: '身份证格式不符',  pattern:/^[1-9][0-9]{5}([1][9][0-9]{2}|[2][0][0|1][0-9])([0][1-9]|[1][0|1|2])([0][1-9]|[1|2][0-9]|[3][0|1])[0-9]{3}([0-9]|[X])$/ }],
              })(<Input placeholder="正规身份证号格式" />)}
          </FormItem>
        </Col>

    </Row>
    
    <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
    
        <Col md={12} sm={24}>
          <FormItem  label="员工照片">
              {getFieldDecorator('photo',{
                rules: [{ required: false, message: '请选择员工照片！'}],
              })(
              	<div className={styles.staffPhotoContainer} onClick={this.staffPhotoShow}>
      		      	<svg className={`${styles.icon} ${styles.staffPhoto}` } aria-hidden="true">
			          <use xlinkHref="#icon-tupian"></use>
			        </svg>
			        <span className={styles.staffPhotoNum}>{photoNum}张图片</span>
              	</div>
              )}
          </FormItem>
        </Col>

        <Col md={12} sm={24}>
          <FormItem  label="出生日期">
              {getFieldDecorator('date_of_birth')(<DatePicker  format="YYYY-MM-DD" style={{ width: '100%' }} placeholder="请选择"/>)}
          </FormItem>
        </Col>

    </Row>
    
    <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
    
    	<Col  md={12} sm={24}>
	        <FormItem  label="籍贯">
	            {getFieldDecorator('place_of_origin', {
	            rules: [{ required: false }],
	            })(<Cascader options={cascaderList != undefined?cascaderList.list:null} onChange={this.onChange} placeholder="请选择" changeOnSelect />)}
	        </FormItem>
        </Col>

		<Col md={12} sm={24}>
          <FormItem  label="户籍所在地">
              {getFieldDecorator('place_of_domicile',{
              rules: [{ required: false, message: '最多输入40个字符',max: 40}],
              })(<Input placeholder="1-40个字符" />)}
          </FormItem>
        </Col>

    </Row>
	
	<Row gutter={{ md: 8, lg: 24, xl: 48 }}>
    
        <Col md={12} sm={24}>
          <FormItem  label="个人邮箱">
              {getFieldDecorator('email', {
              rules: [{ required: false, message: '邮箱格式不符', pattern:/^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/}],
              })(<Input placeholder="正规邮箱地址"/>)}
          </FormItem>
        </Col>

        <Col md={12} sm={24}>
          <FormItem  label="紧急联系人">
              {getFieldDecorator('emergency_contact_name',{
              	rules: [{ required: false, message: '最多输入10个字符',max: 10}],
              })(<Input placeholder="1-10个字符" />)}
          </FormItem>
        </Col>

    </Row>
    
	<Row gutter={{ md: 8, lg: 24, xl: 48 }}>
    
        <Col md={12} sm={24}>
          <FormItem  label="紧急联系电话">
              {getFieldDecorator('emergency_contact_phone',{
              	rules: [{ required: false, message: '最多输入13个字符',max: 13}],
              })(<Input placeholder="1-13个字符"/>)}
          </FormItem>
        </Col>

        <Col md={12} sm={24}>
          <FormItem  label="银行卡号">
              {getFieldDecorator('bank_card_number',{
              	rules: [{ required: false, message: '银行卡号格式不符', pattern:/^([1-9]{1})(\d{14}|\d{18})$/}],
              })(<InputNumber placeholder="10-20位数字" style={{width: '100%'}}/>)}
          </FormItem>
        </Col>

    </Row>
    <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
    
        <Col md={12} sm={24}>
          <FormItem  label="开户行">
              {getFieldDecorator('open_bank')(<Input placeholder="请具体到支行" />)}
          </FormItem>
        </Col>

        <Col md={12} sm={24}>
          <FormItem  label="入职日期">
              {getFieldDecorator('entry_time', {
              rules: [{ required: true, message: '请选择入职日期'}],
              initialValue: moment(new Date()),
              })(<DatePicker  format="YYYY-MM-DD" style={{ width: '100%' }} placeholder="请选择"/>)}
          </FormItem>
        </Col>

    </Row>
    <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
    
        <Col md={12} sm={24}>
          <FormItem  label="部门">
              {getFieldDecorator('dept')(
              	<SelectDeptTree {...parentDeptTreeMethod}/>
              )}
          </FormItem>
        </Col>
        
        <Col md={12} sm={24}>
	        <FormItem label="岗位">
	            {getFieldDecorator('post')(
	                <Select labelInValue placeholder="请选择" style={{ width: '100%' }}>
	                	{postForUser != undefined?postForUser.list.map((item,index) => {
	                		return <Option value={item.id}>{item.post_name}</Option>
	                	}):null}
	                </Select>
	            )}
	        </FormItem>
        </Col>

    </Row>
    
    <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
    
        <Col md={12} sm={24}>
          <FormItem  label="聘用形式">
              {getFieldDecorator('from_of_employment',{
              	rules: [{ required: true, message: '请选择聘用形式'}],
              	initialValue: "1",
              })(
              	<Select placeholder="请选择" style={{ width: '100%' }} onChange={this.handleChange}>
                    <Select.Option key="1">正式</Select.Option>
                    <Select.Option key="0">非正式</Select.Option>
                </Select>
              )}
          </FormItem>
        </Col>
		{flag == "1"?(
			<Col md={12} sm={24}>
	          <FormItem  label="转正日期(正式)">
	              {getFieldDecorator('become_worker_time')(<DatePicker  format="YYYY-MM-DD" style={{ width: '100%' }} placeholder="请选择"/>)}
	          </FormItem>
	        </Col>
		):(
			<Col md={12} sm={24}>
	          <FormItem  label="非正式类型">
	              {getFieldDecorator('become_worker_type', {
	              rules: [{ required: false, message: '请选择非正式类型'}],
	              initialValue: "1",
	              })(
	              	<Select placeholder="请选择" style={{ width: '100%' }}>
	                    <Select.Option key="1">实习</Select.Option>
	                    <Select.Option key="2">劳务</Select.Option>
	                    <Select.Option key="3">顾问</Select.Option>
	                    <Select.Option key="4">返聘</Select.Option>
	                    <Select.Option key="5">外包</Select.Option>
	                </Select>
	              )}
	          </FormItem>
	        </Col>
		)}


    </Row>
    <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
    
        <Col md={12} sm={24}>
          <FormItem  label="管理形式">
              {getFieldDecorator('management_form',{
              	rules: [{ required: false, message: '请选择管理形式'}],
              })(
              	<Select placeholder="请选择" style={{ width: '100%' }}>
                    <Select.Option key="1">总部</Select.Option>
                    <Select.Option key="2">分城市</Select.Option>
                </Select>
              )}
          </FormItem>
        </Col>
		
		<Col md={12} sm={24}>
          <FormItem  label="工号">
              {getFieldDecorator('job_number',{
              	rules: [{ required: false, message: '最多输入20个字符',max: 20}],
              })(<Input placeholder="1-20个字符" />)}
          </FormItem>
        </Col>


    </Row>
	<Row gutter={{ md: 8, lg: 24, xl: 48 }}>

    	<Col  md={12} sm={24}>
	        <FormItem  label="工作城市">
	            {getFieldDecorator('working_city', {
	            rules: [{ required: false }],
	            })(<Cascader options={cascaderList != undefined?cascaderList.list:null} onChange={this.onChange} placeholder="请选择" changeOnSelect />)}
	        </FormItem>
        </Col>

    </Row>
    <Row>
    	<Col style={{textAlign: 'center'}}>
            <Button size="large" style={{marginRight: '10px'}} onClick={() => router.push('/staff/staffinfo')}>取消</Button>
            <Button size="large" type="primary" htmlType="submit">提交</Button>
        </Col>
    </Row>

  </Form>

      </div>
    </Card>
    </PageHeaderWrapper>
    )

  }
}

export default StaffCreateForm;